import Mock from "mockjs";
//处理路径传参
import data from "@/assets/data.json";
import dayjs from "dayjs";
import { handleAi } from "./ai";

function excelDateToJSDate(serial) {
  if (typeof serial !== "number") return serial;

  // Excel 的日期系统从 1900-01-01 开始，但有个错误（认为1900是闰年）
  const utc_days = Math.floor(serial - 25569);
  const utc_value = utc_days * 86400; // 86400 = 24 * 60 * 60
  const date_info = new Date(utc_value * 1000);

  // 处理 Excel 的日期系统错误（1900年2月29日不存在）
  if (serial >= 60) {
    date_info.setUTCDate(date_info.getUTCDate() - 1);
  }

  return dayjs(date_info).isValid()
    ? dayjs(date_info).add(1, "day").format("YYYY-MM-DD")
    : "";
}
// 导出时间处理
data.forEach((item) => {
  item.诉求时间 = excelDateToJSDate(item.诉求时间);
  item.挂机时间 = excelDateToJSDate(item.挂机时间);
  item.受理时间 = excelDateToJSDate(item.受理时间);
  item.归档时间 = excelDateToJSDate(item.归档时间);
  item.处理时限 = excelDateToJSDate(item.处理时限);
});

function ArrSet(Arr: any[], id: string): any[] {
  let obj: any = {};
  const arrays = Arr.reduce((setArr, item) => {
    obj[item[id]] ? "" : (obj[item[id]] = true && setArr.push(item));
    return setArr;
  }, []);
  return arrays;
}
/**
 * @description: min ≤ r ≤ max  随机数
 * @param {*} Min
 * @param {*} Max
 * @return {*}
 */
function RandomNumBoth(Min: any, Max: any) {
  var Range = Max - Min;
  var Rand = Math.random();
  var num = Min + Math.round(Rand * Range); //四舍五入
  return num;
}
// 处理状态统计
const handleDataCount = (val, key = "处理状态") => {
  const statusCount = {};
  val.forEach((item) => {
    const status = item[key];
    statusCount[status] = (statusCount[status] || 0) + 1;
  });

  return statusCount;
};

// 将对象转换为数组并取前10
const getTop10Lines = (val) => {
  // 将对象转换为数组并过滤掉空键
  const entries = Object.entries(val).filter(([key]) => key !== "");
  // 按值降序排序
  const sorted = entries.sort((a, b) => b[1] - a[1]);
  // 取前10个
  const top10 = sorted.slice(0, 10);
  return top10.map((item) => ({ name: item[0], value: item[1] }));
  // 转换回对象
  // return Object.fromEntries(top10);
};
// 将对象转换为数组
const getLines = (val) => {
  // 将对象转换为数组并过滤掉空键
  const entries = Object.entries(val).filter(([key]) => key !== "");
  // 按值降序排序
  const sorted = entries.sort((a, b) => b[1] - a[1]);
  // 取前10个
  const top10 = sorted;
  return top10.map((item) => ({ name: item[0], value: item[1] }));
  // 转换回对象
  // return Object.fromEntries(top10);
};

// 工单类型分布
export default [
  {
    url: "/bigscreen/countUserNum",
    type: "get",
    response: () => {
      const a = Mock.mock({
        success: true,
        // data: [
        //   {
        //     value: 36,
        //     name: "咨询查询",
        //   },
        //   {
        //     value: 28,
        //     name: "用电业务",
        //   },
        // ],
        data: getTop10Lines(handleDataCount(data, "业务类型")),
      });
      a.data.onlineNum =
        a.data.totalNum - a.data.offlineNum - a.data.lockNum - a.data.alarmNum;
      return a;
    },
  },
  //智能体运行日志
  {
    url: "/bigscreen/leftBottom",
    type: "get",
    response: () => {
      const a = Mock.mock({
        success: true,
        data: {
          "list|20": [
            {
              provinceName: "@province()",
              cityName: "@city()",
              countyName: "@county()",
              createTime: "@datetime('yyyy-MM-dd HH:mm:ss')",
              deviceId: "6c512d754bbcd6d7cd86abce0e0cac58",
              "gatewayno|+1": 10000,
              "onlineState|1": [0, 1],
            },
          ],
        },
      });
      return a;
    },
  },
  // 工单涉及台区TOP10,工单涉及线路TOP10
  {
    url: "/bigscreen/ranking",
    type: "post",
    response: (options) => {
      const obj = JSON.parse(options.body);
      // let num = Mock.mock({
      //   "list|80": [{ value: "@integer(50,1000)", name: "@city()" }],
      // }).list;
      // let newNum: any = []
      // num.map((item: any) => {
      //   if (newNum.length < 15) {
      //     newNum.push(item);
      //   }
      // });
      // let arr = newNum.sort((a: any, b: any) => {
      //   return b.value - a.value;
      // });
      let a = {
        success: true,
        data: getTop10Lines(handleDataCount(data, obj.type)),
      };
      return a;
    },
  },
  //责任人签收/处理工单分布
  {
    url: "/bigscreen/installationPlan",
    type: "get",
    response: () => {
      let num = RandomNumBoth(10, 10);
      const a: any = {};
      // const a = Mock.mock({
      //   ["category|" + num]: ["@cname()"],
      //   ["barData|" + num]: ["@integer(10, 100)"],
      // });
      // let lineData = [],
      //   rateData = [];
      // for (let index = 0; index < num; index++) {
      //   let lineNum = Mock.mock("@integer(0, 100)") + a.barData[index];
      //   lineData.push(lineNum);
      //   let rate = a.barData[index] / lineNum;
      // }
      const category: string[] = [];
      const barData: string[] = []; // 签收工单数
      const lineData: string[] = []; // 处理工单数
      const barDataObj: any = {};
      const lineDataObj: any = {};
      data.forEach((item) => {
        const name = item.负责人;
        if (name) {
          if (!category.includes(name)) {
            category.push(name);
          }
          if (
            [
              "网级坐席答复",
              "网级处置终审",
              "后续跟踪反馈审核",
              "省班长答复",
              "省级处置审核",
            ].includes(item.当前环节)
          ) {
            lineDataObj[name] = (lineDataObj[name] || 0) + 1;
          }

          if (item.处理状态.trim() === "处理") {
            barDataObj[name] = (barDataObj[name] || 0) + 1;
          }
        }
      });
      category.forEach((name) => {
        barData.push(barDataObj[name]);
        lineData.push(lineDataObj[name]);
      });

      a.barData = barData;
      a.lineData = lineData;
      a.category = category;
      return {
        success: true,
        data: a,
      };
    },
  },
  {
    url: "/bigscreen/ai",
    type: "post",
    response: (options: any) => {
      const a = Mock.mock({
        success: true,
        data: handleAi(JSON.parse(options.body)),
      });
      return a;
    },
  },
  {
    url: "/bigscreen/table",
    type: "post",
    response: (options: any) => {
      return {
        success: true,
        data
      };
    },
  },
];
